import { Carousel } from 'antd'
import * as echarts from 'echarts'
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from 'react'
import CountUp from 'react-countup'
import Slider from 'react-slick'

import LengedDataBox from './LengedDataBox'
// import { FlipCard } from "../Compoments/FlipCard"

import 'animate.css'
import 'slick-carousel/slick/slick-theme.css'
import 'slick-carousel/slick/slick.css'

export type OptionData = {
  label: string
  value: string
}

export const BigPre2 = forwardRef<{ resize: () => void }, any>(
  ({ data, color }, ref) => {
    const chartDom = useRef<HTMLDivElement>(null)
    const myChart = useRef<echarts.EChartsType>()
    const [activeIndex, setIndex] = useState<number>(-1)
    const timerPieRef = useRef<any>(null)
    const [settings, setSetings] = useState<any>({
      dots: false, // 隐藏轮播小圆点
      infinite: true,
      slidesToShow: 6, // 展示6条内容
      speed: 500,
      autoplay: true,
      vertical: true, // 垂直
      autoplaySpeed: 2000,
      pauseOnHover: true, // 鼠标悬浮不暂停
      arrows: false // 隐藏翻页箭头
    })
    const clickFun = (index: number) => {
      if (timerPieRef.current) clearInterval(timerPieRef.current)
      setIndex(index)
      data.map((v: any, i: number) => {
        // 取消之前高亮的图形
        myChart.current?.dispatchAction({
          type: 'downplay',
          seriesIndex: 0,
          dataIndex: i
        })
      })
      myChart.current?.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: index
      })
    }

    /*获取图表数据*/
    useEffect(() => {
      if (!chartDom.current) {
        return
      }
      const optData = data?.filter((v: OptionData) => v.value)
      let fData: any[] = []
      if (optData.length) {
        fData = data
      }
      const data2 = fData?.map((v: any, i: number) => {
        return {
          ...v,
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: color[i][0] }, // 0% 处的颜色
                { offset: 1, color: color[i][1] } // 100% 处的颜色
              ],
              global: false // 缺省为 false
            }
          }
        }
      })
      if (!myChart.current) {
        // 初始化值
        myChart.current = echarts.init(chartDom.current, null, {
          renderer: 'canvas'
        })
      }
      myChart.current.setOption({
        showEmptyCircle: true,
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['68%', '90%'],
            center: ['center', 'center'],
            // padAngle: 4,
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
            itemStyle: {
              // borderRadius: 10,
              borderColor: '#181818',
              borderWidth: 2
            },
            avoidLabelOverlap: true,
            animation: true,
            hoverAnimation: true,
            emphasis: {
              scale: true,
              scaleSize: 8,
              label: {
                show: false
              }
            },
            data: data2,
            emptyCircleStyle: {
              color: 'rgba(0, 0, 0, 0.60)' // 设置没数据的样式
            }
          }
        ]
      })

      myChart.current.on('mouseout', function (params) {
        clearInterval(timerPieRef.current)
        startPieTime()
      })
      myChart.current.on('click', function (params) {
        clickFun(params.dataIndex)
      })
    }, [data])
    useEffect(() => {
      return () => {
        if (myChart.current && !myChart.current.isDisposed()) {
          echarts.dispose(myChart.current)
        }
      }
    }, [])
    useEffect(() => {
      setSetings({
        ...settings,
        slidesToShow: data && data.length > 5 ? 6 : data.length
      })
      if (timerPieRef.current) clearInterval(timerPieRef.current)
      startPieTime()
    }, [data])

    const startPieTime = () => {
      let currentIndex = activeIndex
      if (data && myChart.current) {
        timerPieRef.current = setInterval(function () {
          if (myChart.current) {
            const dataLen = data.length
            currentIndex = currentIndex < dataLen - 1 ? currentIndex + 1 : 0
            setIndex(currentIndex)
            // 取消之前高亮的图形
            data.map((v: any, i: number) => {
              // 取消之前高亮的图形
              myChart.current?.dispatchAction({
                type: 'downplay',
                seriesIndex: 0,
                dataIndex: i
              })
            })
            // 高亮当前图形
            myChart.current.dispatchAction({
              type: 'highlight',
              seriesIndex: 0,
              dataIndex: currentIndex
            })
          }
        }, 2411)
      }
    }
    // 设置定时器，间隔几秒切换选中状态
    useEffect(() => {
      // 组件卸载时清除定时器
      return () => {
        if (timerPieRef.current) {
          clearInterval(timerPieRef.current)
        }
      }
    }, [])

    // 图例轮播的配置
    const sliderRef = useRef<any>(null)
    // useEffect(() => {
    //   sliderRef.current.slickGoTo(activeIndex)
    // }, [activeIndex])

    //体积占比的动画
    const [playAnimation, setPlayAnimation] = useState(false)
    useEffect(() => {
      startAnimation()
    }, [activeIndex])
    const startAnimation = () => {
      setPlayAnimation(true)
      setTimeout(() => {
        setPlayAnimation(false)
      }, 3000) // 5秒后停止动画
    }

    /*视口改变 echarts  -resize*/
    useImperativeHandle(ref, () => ({
      resize: () => {
        if (myChart.current) {
          // console.log("--right--BigPire--resize--")
          myChart.current.resize()
        }
      }
    }))

    return (
      <div
        className="pie-box flexr alc juc"
        style={{ position: 'relative', height: '100%' }}
      >
        <div
          className="flexr alc juc"
          style={{ position: 'relative', width: 398, height: '100%' }}
        >
          {/* 环形图 */}
          <div className="flexr alc juc" style={{ position: 'relative' }}>
            {/* 环形图 -中间的数据*/}
            <div className="card-abs">
              <div
                className="item-p"
                style={{ color: color[activeIndex]?.[2] }}
              >
                <CountUp
                  start={0}
                  end={
                    data && activeIndex > -1
                      ? data[activeIndex]?.piont
                      : (data && data[0]?.piont) || 0
                  }
                  duration={1}
                  decimals={2}
                ></CountUp>
                <span className="p-t">%</span>
              </div>
              <CarouselBox
                data={data}
                dataIndex={activeIndex || 0}
                color={color}
              ></CarouselBox>
            </div>
            {/* 环形图 -本身*/}
            <div
              ref={chartDom}
              style={{ width: '152px', minHeight: '152px' }}
              className="echarts-pie"
            ></div>
            {/**渐入 */}
            {/* {data && data[activeIndex] && data[activeIndex].kvs?.length ? (
            <div
              className={
                playAnimation
                  ? "animate__animated animate__fadeInLeft FadeIn_box flexr alc jub"
                  : "FadeIn_box flexr alc jub"
              }
            >
              <IconFont type="icon-xiangyou" style={{ color: "#F66E2C" }} />
              <div className="FadIn_box_content">
                <div className="f_b_t">{data[activeIndex]?.name}</div>
                {data && activeIndex > -1 && data[activeIndex]
                  ? data[activeIndex].kvs?.map((v: any, i: number) => {
                      return (
                        <div className="f_li flexr alc jub" key={i}>
                          <div>
                            <span className="f_txt">{v.name}</span>
                            <span>m³</span>
                          </div>
                          <div>
                            <span className="f_txt">{v.value}</span>
                            <span>辆</span>
                          </div>
                          <div>
                            <span className="f_txt">{v.piont}</span>
                            <span>%</span>
                          </div>
                        </div>
                      )
                    })
                  : null}
              </div>
            </div>
          ) : null} */}
          </div>

          {/* 环形图 - 右侧图例*/}
          <div className="SliderContent2">
            {data.length > 6 ? (
              <>
                {' '}
                <Slider ref={sliderRef} {...settings}>
                  {data.map((item: any, i: number) => {
                    return (
                      <LengedDataBox
                        label={item.name}
                        value={item.piont}
                        key={i}
                        color={color[i]?.[2]}
                      ></LengedDataBox>
                    )
                  })}
                </Slider>
              </>
            ) : (
              <>
                {' '}
                {data.map((item: any, i: number) => {
                  return (
                    <LengedDataBox
                      label={item.name}
                      value={item.piont}
                      key={i}
                      color={color[i]?.[2]}
                    ></LengedDataBox>
                  )
                })}
              </>
            )}
          </div>
        </div>
      </div>
    )
  }
)
function CarouselBox({
  data,
  dataIndex,
  color
}: {
  data: any[]
  dataIndex: number
  color: any[]
}) {
  const carouselRef = useRef<any>(null)
  useEffect(() => {
    carouselRef.current.goTo(dataIndex)
  }, [dataIndex])
  return (
    <div className="CarouselBox">
      <Carousel
        ref={carouselRef}
        effect="fade"
        speed={1800}
        dots={false}
        adaptiveHeight={true}
      >
        {data?.map((item, i) => {
          return (
            <div className="CarouselBox-item" key={i}>
              <div className="item-n">{item.name}</div>
            </div>
          )
        })}
      </Carousel>
    </div>
  )
}
